package org.jeecg.modules.kc.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.kc.entity.*;
import org.jeecg.modules.kc.enums.OutBoundEnum;
import org.jeecg.modules.kc.enums.StorageEnum;
import org.jeecg.modules.kc.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.pos.entity.PosType;
import org.jeecg.modules.rooms.entity.CesGoods;
import org.jeecg.modules.rooms.entity.CesGoodsUnit;
import org.jeecg.modules.rooms.service.CesGoodsServiceImpl;
import org.jeecg.modules.rooms.service.CesGoodsUnitServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: kc_stock
 * @Author: jeecg-boot
 * @Date:   2023-04-18
 * @Version: V1.0
 */
@Api(tags="kc_stock")
@RestController
@RequestMapping("/kc/kcStock")
@Slf4j
public class KcStockController extends JeecgController<KcStock, IKcStockService> {
	@Autowired
	private IKcStockService kcStockService;
	@Autowired
	private IKcSupplierInGoodsService kcSupplierInGoodsService;
	@Autowired
	private IKcGoodsService kcGoodsService;
	@Autowired
	private CesGoodsUnitServiceImpl cesGoodsUnitService;
	@Autowired
	private IKcDepositoryService kcDepositoryService;
	@Autowired
	private IKcSupplierService kcSupplierService;
	@Autowired
	private IKcStockDetailService kcStockDetailService;
	@Autowired
	private  IKcDepositoryInGoodsService kcDepositoryInGoodsService;

	 @Autowired
	 private CesGoodsServiceImpl cesGoodsService;
	/**
	 * 分页列表查询
	 *
	 * @param kcStock
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "kc_stock-分页列表查询")
	@ApiOperation(value="kc_stock-分页列表查询", notes="kc_stock-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<KcStock>> queryPageList(KcStock kcStock,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<KcStock> queryWrapper = QueryGenerator.initQueryWrapper(kcStock, req.getParameterMap());
		Page<KcStock> page = new Page<KcStock>(pageNo, pageSize);
		IPage<KcStock> pageList = kcStockService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			KcDepository kcDepository = kcDepositoryService.getById(item.getDepositoryId());
			if (kcDepository != null) {
				item.setDepositoryName(kcDepository.getName());
			}
			KcSupplier kcSupplier = kcSupplierService.getById(item.getSupplierId());
			if (kcSupplier != null) {
				item.setSupplierName(kcSupplier.getName());
			}
			if (item.getType().equals(2)) {
				StorageEnum storageEnum = StorageEnum.val(item.getStockType());
				if (storageEnum != null) {
					item.setStockTypeName(storageEnum.getTitle());
				}
			}
			if (item.getType().equals(1)) {
				OutBoundEnum outBoundEnum = OutBoundEnum.val(item.getStockType());
				if (outBoundEnum != null) {
					item.setStockTypeName(outBoundEnum.getTitle());
				}
			}
		});
		return Result.OK(pageList);
	}

	 /**
	  * 入库类型列表
	  * @return
	  */
	 @ApiOperation(value="入库类型列表", notes="入库类型列表")
	 @GetMapping(value = "/storageTypeList")
	 public Result<List<DictModel>> storageTypeList() {
		 return Result.OK(StorageEnum.getDictList());
	 }

	 /**
	  * 出库类型列表
	  * @return
	  */
	 @ApiOperation(value="出库类型列表", notes="出库类型列表")
	 @GetMapping(value = "/outBoundTypeList")
	 public Result<List<DictModel>> outBoundTypeList() {
		 return Result.OK(OutBoundEnum.getDictList());
	 }


	/**
	 *   出入库添加
	 *
	 * @param kcStock
	 * @return
	 */
	@AutoLog(value = "出入库添加")
	@ApiOperation(value="出入库添加", notes="出入库添加")
	//@RequiresPermissions("kc:kc_stock:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody KcStock kcStock) {
		if (ObjectUtils.isEmpty(kcStock.getStockDetailList())) {
			return Result.error("请先选择商品");
		}
		service.add(kcStock);
		return Result.OK("添加成功！");
	}

	 /**
	  * 出入库审核
	  * @param kcStock
	  * @return
	  */
	 @ApiOperation(value="审核", notes="审核")
	 @PostMapping(value = "/audit")
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> audit(@RequestBody KcStock kcStock) {
		 service.audit(kcStock);
		 return Result.OK("审核成功!");
	 }

	/**
	 *  编辑
	 *
	 * @param kcStock
	 * @return
	 */
	@AutoLog(value = "kc_stock-编辑")
	@ApiOperation(value="kc_stock-编辑", notes="kc_stock-编辑")
	//@RequiresPermissions("kc:kc_stock:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody KcStock kcStock) {
		if (ObjectUtils.isEmpty(kcStock.getStockDetailList())) {
			return Result.error("请先选择商品");
		}
		String stockInfo = "";
		for (KcStockDetail kcStockDetail : kcStock.getStockDetailList()) {
			if (kcStock.getType().equals(2)) {
				KcSupplierInGoods kcSupplierInGoods = kcSupplierInGoodsService.getById(kcStockDetail.getSupplierInGoodsId());
				if (kcSupplierInGoods != null) {
					CesGoods cesGoods = cesGoodsService.getById(kcSupplierInGoods.getGoodsId());
					if (cesGoods != null) {
						kcStockDetail.setCesGoods(cesGoods);
						CesGoodsUnit cesGoodsUnit = cesGoodsUnitService.getById(cesGoods.getGoodUnit());
						if (cesGoodsUnit != null) {
							stockInfo += cesGoods.getName() + kcStockDetail.getNum() + cesGoodsUnit.getName() + ",";
						}
					}
				}
			} else if (kcStock.getType().equals(1)) {
				KcDepositoryInGoods kcDepositoryInGoods = kcDepositoryInGoodsService.getById(kcStockDetail.getSupplierInGoodsId());
				if (kcDepositoryInGoods != null) {
					CesGoods cesGoods = cesGoodsService.getById(kcDepositoryInGoods.getGoodsId());
					if (cesGoods != null) {
						kcStockDetail.setCesGoods(cesGoods);
						CesGoodsUnit cesGoodsUnit = cesGoodsUnitService.getById(cesGoods.getGoodUnit());
						if (cesGoodsUnit != null) {
							stockInfo += cesGoods.getName() + kcStockDetail.getNum() + cesGoodsUnit.getName() + ",";
						}
					}
				}
			}
		}
		kcStock.setStockInfo(stockInfo);
		kcStockService.updateById(kcStock);

		LambdaQueryWrapper<KcStockDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(KcStockDetail::getStockId, kcStock.getCode());
		kcStockDetailService.remove(lambdaQueryWrapper);

		for (KcStockDetail kcStockDetail : kcStock.getStockDetailList()) {
			kcStockDetail.setHotelId(kcStock.getHotelId());
			kcStockDetail.setTenantId(TokenUtils.currentTenantId());
			kcStockDetail.setStockId(kcStock.getCode());
			kcStockDetail.setId("");
		}
		kcStockDetailService.saveBatch(kcStock.getStockDetailList());

		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "kc_stock-通过id删除")
	@ApiOperation(value="kc_stock-通过id删除", notes="kc_stock-通过id删除")
	//@RequiresPermissions("kc:kc_stock:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		KcStock kcStock = kcStockService.getById(id);
		if (kcStock.getStatus().equals(1)) {
			return Result.error("审核通过不能删除");
		}
		LambdaQueryWrapper<KcStockDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(KcStockDetail::getStockId, kcStock.getCode());
		kcStockDetailService.remove(lambdaQueryWrapper);
		kcStockService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "kc_stock-批量删除")
	@ApiOperation(value="kc_stock-批量删除", notes="kc_stock-批量删除")
	//@RequiresPermissions("kc:kc_stock:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.kcStockService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "kc_stock-通过id查询")
	@ApiOperation(value="kc_stock-通过id查询", notes="kc_stock-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<KcStock> queryById(@RequestParam(name="id",required=true) String id) {
		KcStock kcStock = kcStockService.getById(id);
		if(kcStock==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(kcStock);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param kcStock
    */
    //@RequiresPermissions("kc:kc_stock:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KcStock kcStock) {
        return super.exportXls(request, kcStock, KcStock.class, "kc_stock");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("kc:kc_stock:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, KcStock.class);
    }

}
